package cn.wolfcode.rbac.web.controller;

import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.service.IRoleService;
import cn.wolfcode.rbac.util.JsonResult;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    //@RequiresPermissions("role:list")
    //@RequriedPermission(name="角色列表",expression="role:list")
    @RequestMapping("/list")
    public String list(@ModelAttribute("qo")QueryObject qo, Model model){
        PageInfo pageInfo = this.roleService.query(qo);
        model.addAttribute("result",pageInfo);
        return "role/list";
    }

    //@RequiresPermissions("role:delete")
    //@RequriedPermission(name="角色删除",expression="role:delete")
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            this.roleService.delete(id);
            return new JsonResult("操作成功",true);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult("操作失败",false);
        }
    }

    //@RequiresPermissions("role:input")
    @RequestMapping("/input")
    public String input(Long id,Model model){
        //查询权限的信息，显示在页面中
        model.addAttribute("permissions",this.permissionService.list());
        if(id != null){
            model.addAttribute("entity",this.roleService.get(id));
        }
        return "role/input";
    }

    //@RequiresPermissions("role:saveOrUpdate")
    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Role entity, Long[]ids) {
       try {
           this.roleService.saveOrUpdate(entity,ids);
           return new JsonResult("操作成功",true);
       }catch (Exception e){
           e.printStackTrace();
           return new JsonResult("操作失败",false);
       }
    }

}
